<template>
  <el-card class="annex-card" shadow="hover">
    <div slot="header" class="clearfix header-bar">
      <span>附件管理</span>
      <div class="actions">
        <el-checkbox
          v-model="selectAll"
          @change="handleSelectAll"
          style="margin-right: 10px"
          >全选</el-checkbox
        >
        <el-button
          type="danger"
          size="small"
          :disabled="selectedFiles.length === 0"
          @click="handleBatchDelete"
          style="margin-right: 10px"
          >批量删除</el-button
        >
        <el-button type="primary" size="small" @click="dialogVisible = true"
          >上传文件</el-button
        >
      </div>
    </div>
    <div class="file-cards">
      <el-card
        v-for="file in fileList"
        :key="file.uid"
        class="file-card"
        :body-style="{ padding: '10px' }"
      >
        <div class="file-card-header">
          <el-checkbox
            v-model="selectedFiles"
            :label="file.uid"
            @change="handleSelectChange"
          ></el-checkbox>
          <i class="file-icon" :class="getFileIcon(file.name)"></i>
          <el-tooltip :content="file.name" placement="top">
            <span class="file-name" @click="handlePreview(file)">
              {{ file.name }}
            </span>
          </el-tooltip>
          <el-button
            type="text"
            size="mini"
            @click="handleRemove(file)"
            style="margin-left: auto"
            >删除</el-button
          >
        </div>
        <div class="file-meta">
          <span>{{ formatFileSize(file.size || 0) }}</span>
          <span style="margin-left: 8px">{{
            file.uploadTime || "未知时间"
          }}</span>
        </div>
      </el-card>
      <div v-if="fileList.length === 0" class="empty-tip">
        暂无附件，请上传文件
      </div>
    </div>

    <!-- 上传文件模态框 -->
    <el-dialog
      title="上传文件"
      :visible.sync="dialogVisible"
      width="400px"
      @close="resetUpload"
    >
      <el-upload
        ref="upload"
        class="upload-drag"
        drag
        :http-request="customUpload"
        :file-list="[]"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
        :auto-upload="false"
        multiple
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传不超过 10MB 的文件</div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUpload">上传</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
export default {
  name: "AnnexPages",
  data() {
    return {
      fileList: [
        {
          name: "项目需求文档.docx",
          url: "https://example.com/项目需求文档.docx",
          uid: "1",
        },
        {
          name: "设计稿.png",
          url: "https://example.com/设计稿.png",
          uid: "2",
        },
        {
          name: "说明.txt",
          url: "https://example.com/说明.txt",
          uid: "3",
        },
      ],
      selectedFiles: [],
      selectAll: false,
      dialogVisible: false,
    };
  },
  watch: {
    selectedFiles(val) {
      this.selectAll =
        val.length === this.fileList.length && this.fileList.length > 0;
    },
    fileList(val) {
      if (val.length === 0) {
        this.selectedFiles = [];
        this.selectAll = false;
      }
    },
  },
  methods: {
    handlePreview(file) {
      window.open(file.url, "_blank");
    },
    handleRemove(file) {
      this.fileList = this.fileList.filter((f) => f.uid !== file.uid);
      this.selectedFiles = this.selectedFiles.filter((uid) => uid !== file.uid);
      this.$message.success(`已移除文件：${file.name}`);
    },
    handleBatchDelete() {
      this.fileList = this.fileList.filter(
        (f) => !this.selectedFiles.includes(f.uid)
      );
      this.selectedFiles = [];
      this.$message.success("已批量删除选中文件");
    },
    handleSelectAll(val) {
      if (val) {
        this.selectedFiles = this.fileList.map((f) => f.uid);
      } else {
        this.selectedFiles = [];
      }
    },
    handleSelectChange() {
      // 由 watch 自动处理 selectAll 状态
    },
    getFileIcon(filename) {
      const extension = filename.split(".").pop().toLowerCase();
      const icons = {
        pdf: "el-icon-document",
        doc: "el-icon-document",
        docx: "el-icon-document",
        xls: "el-icon-document",
        xlsx: "el-icon-document",
        ppt: "el-icon-document",
        pptx: "el-icon-document",
        txt: "el-icon-document",
        jpg: "el-icon-picture",
        jpeg: "el-icon-picture",
        png: "el-icon-picture",
        gif: "el-icon-picture",
        zip: "el-icon-folder",
        rar: "el-icon-folder",
        mp3: "el-icon-video-play",
        mp4: "el-icon-video-play",
      };
      return icons[extension] || "el-icon-document";
    },
    formatFileSize(bytes) {
      if (bytes === 0) return "0 Bytes";
      const k = 1024;
      const sizes = ["Bytes", "KB", "MB", "GB"];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(1) + " " + sizes[i]);
    },
    handleSuccess(response, file) {
      // 静态演示，实际应从 response 获取文件信息
      const newFile = {
        name: file.name,
        url: "#",
        uid: Date.now().toString() + Math.random(),
      };
      this.fileList.push(newFile);
      this.$message.success(`上传成功：${file.name}`);
    },
    beforeUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error("上传文件大小不能超过 10MB!");
      }
      return isLt10M;
    },
    submitUpload() {
      this.$refs.upload.submit();
      this.dialogVisible = false;
    },
    resetUpload() {
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles();
      }
    },
    customUpload(option) {
      // 模拟上传成功
      setTimeout(() => {
        this.handleSuccess({}, option.file);
        option.onSuccess({}, option.file);
      }, 500);
    },
  },
};
</script>

<style scoped>
.annex-card {
  width: 100%;
  height: 100%;
  min-height: 400px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  border-radius: 8px;
}
.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  border-bottom: 1px solid #ebeef5;
}
.header-bar span {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}
.actions {
  display: flex;
  align-items: center;
}
.file-cards {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  min-height: 120px;
  padding: 8px;
}
.file-card {
  width: 180px;
  min-height: 80px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: center;
  transition: all 0.3s ease;
  border-radius: 6px;
  margin: 8px;
}
.file-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.file-card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
}
.file-name {
  flex: 1;
  cursor: pointer;
  color: #409eff;
  margin-left: 8px;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100px;
}
.file-name:hover {
  text-decoration: underline;
}
.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  padding: 40px 0;
  width: 100%;
}
.empty-tip::before {
  content: "📁";
  font-size: 48px;
  margin-bottom: 16px;
}
.upload-drag {
  width: 100%;
}
.file-icon {
  font-size: 24px;
  color: #67c23a;
  margin-right: 8px;
}
.file-meta {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>
